package com.xzjt.web.aspect;



import com.xzjt.common.utils.IpUtils;
import com.xzjt.web.annotation.SysLogAnnotation;
import com.xzjt.web.entity.SysLog;
import com.xzjt.web.entity.SysUser;
import com.xzjt.web.service.SysLogService;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.util.Date;

/**
 * @author yuandong
 * @date 2021/9/11 10:30
 * 系统日志切面类
 */
@Slf4j
@Aspect
@Component
public class SysLogAspect {

    @Autowired
    private SysLogService sysLogService;

    @Autowired
    private HttpServletRequest request;


    /**
     * 定义切点 @Pointcut
     * 在注解的位置切入代码
     */
    @Pointcut("@annotation(com.xzjt.web.annotation.SysLogAnnotation)")
    public void logPointCut() {}


    /**
     * 处理完请求后执行
     * @param joinPoint
     */
    @AfterReturning(pointcut = "logPointCut()")
    public void saveSysLog(JoinPoint joinPoint) {

        log.info("开始进入(用户操作)日志切面....");
        //保存日志
        SysLog sysLog = new SysLog();

        //从切面织入点处通过反射机制获取织入点处的方法
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        //获取切入点所在的方法
        Method method = signature.getMethod();

        //获取操作
        SysLogAnnotation myLog = method.getAnnotation(SysLogAnnotation.class);
        if (myLog != null) {
            String value = myLog.value();
            sysLog.setOperation(value);//保存获取的操作
        }

        //获取请求的类名
        String className = joinPoint.getTarget().getClass().getName();
        //获取请求的方法名
        String methodName = method.getName();
        sysLog.setMethod(className + "." + methodName);

        //请求的参数
        Object[] args = joinPoint.getArgs();

        //请求的路径
        sysLog.setUrl(request.getRequestURI());

        sysLog.setLoginTime(new Date());

        //获取用户名
        String username = (String) SecurityUtils.getSubject().getPrincipal();
        sysLog.setUsername(username);


        //获取用户ip地址
        sysLog.setIpaddr(IpUtils.getIpAddr(request));

        //调用service保存SysLog实体类到数据库
        sysLogService.save(sysLog);
    }
}
